import Util from './Util.js'
import Parse from './Parse.js'

export default class Compile {
  constructor(vm, el) {
    this.vm = vm
    this.el = document.querySelector(el)
    //所有的节点
    this.fragment = this.getNodes()
    // 处理数据
    this.compile()
    this.el.appendChild(this.fragment)
  }

  compile() {
    Array.from(this.fragment.childNodes).forEach((node) => {
      if (Util.isElementNode(node)) {
        //标签节点
        this.compileElement(node)
      } else if (Util.isTextNode(node)) {
        //文本节点
        // this.compileTextNode(node)
      }
    })
  }
  // 解析标签就是解析属性
  compileElement(node) {
    Array.from(node.attributes).forEach((attribute) => {
      let { name, value } = attribute
      //自定义指令判断
      if (Util.isDirective(attribute)) {
        const method = name.slice(2)
        Parse[method](this.vm, node, value)
      } else if (Util.isActiveDirective(attribute)) {
        // console.log(name, value)
        const eventName = name.slice(1)
        Parse.on(this.vm, node, eventName, value)
      }
    })
  }

  getNodes() {
    let fragment = document.createDocumentFragment()
    let node
    while ((node = this.el.firstChild)) {
      fragment.appendChild(node)
    }
    return fragment
  }
}
